package jdbc;

import com.mysql.cj.jdbc.Driver;

import java.sql.*;

public class JDBCDemo1 {

    public static void main(String[] args) throws SQLException {
        // 1. 加载数据库驱动
        DriverManager.registerDriver(new Driver());
        // 2. 建立连接
        final String url = "jdbc:mysql://localhost:3306/jdbcdemo?serverTimezone=UTC";  // 数据库 url
        final String user = "root"; // 数据库用户名
        final String password = "123456"; // 数据库密码
        Connection connection = DriverManager.getConnection(url, user, password);
        // 3. 创建 Statement 对象，用于向数据库发送 SQL 语句
        String sql = "SELECT * FROM `user`";
        Statement statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery(sql);
        // 4. 获取 ResultSet 对象，取出数据，此对象代表结果集
        while (resultSet.next()) {
            int id = resultSet.getInt("id");
            String username = resultSet.getString("username");
            String nickname = resultSet.getString("nickname");
            String pwd = resultSet.getString("password");
            System.out.println("id=" + id + "; username=" + username + "; nickname=" + nickname + "; password=" + pwd + '\r');
        }
        // 5. 释放资源，断开与数据库的连接（调用close()方法）
        // 5.1 释放 ResultSet
        resultSet.close();
        // 5.2 释放 Statement
        statement.close();
        // 5.3 释放 Connection
        connection.close();
    }
}
